<?php
/**
 * RedCross Application
 *
 * @copyright TODO: Add copyright notice
 */

class Core_ShiftExchangeController extends Zend_Controller_Action
{
    private $_shiftService;
    private $_memberService;
    private $_shiftRoleService;

    public function init()
    {
        $this->_shiftService = $this->_helper->getService('Core_Service_Shift');
        $this->_memberService = $this->_helper->getService('Core_Service_Member');
        $this->_shiftRoleService = $this->_helper->getService('Core_Service_ShiftRole');
        $this->_shiftExchangeService = $this->_helper->getService('Core_Service_ShiftExchange');
        $this->_authService = $this->_helper->getService('Core_Service_Auth');
    }

    public function exchangeAction()
    {
        // TODO: ACL?
        $this->_helper->acl()->isAllowed('action:core.shift', 'view');

        $request = $this->getRequest();
        $values = $request->getPost();

        if ($request->isPost() && $values['action'] == 'exchange-chosen-member') {
            $targetMemberId = $values['member'];
            $shiftRoleId = $values['shift-role-id'];

            $validator = new Zend_Validate_Int();
            if (!$validator->isValid($targetMemberId) || !$validator->isValid($shiftRoleId)) {
                throw new RedCross_Exception_ValidationFailed();
            }
            $targetMemberId = (int)$targetMemberId;
            $shiftRoleId = (int)$shiftRoleId;

            $loggedInMemberId = $this->view->authInfo()->getMemberId();
            $shiftRole = $this->_shiftRoleService->fetchById($shiftRoleId);
            $targetMember = $this->_memberService->fetchById($targetMemberId);

            // Making sure the shift notification has been sent (i.e. it is 
            // actually visible to the member wanting to exchange shifts)
            if (is_null($shiftRole->notification_sent_time)) {
                throw new RedCross_Exception_ValidationFailed('En vaktutkallelse må ha blitt sendt før et medlem kan bytte vakten.');
            }

            // Making sure logged in user owns the shift role
            if ($loggedInMemberId != $shiftRole->Member->id) {
                throw new RedCross_Exception_ValidationFailed('Det innloggede medlemmet er ikke eier av vaktbyttet.');
            }

            // TODO: Make sure the shift is a future shift?
            $date = new Zend_Date();
            if ($shiftRole->Shift->from_date < $date->get('YYYY-MM-dd HH:mm:ss')) {
                throw new RedCross_Exception_ValidationFailed('Du kan ikke bytte en vakt som er ferdig.');
            }

            // Making sure target member exists
            if (is_null($targetMember)) {
                throw new RedCross_Exception_ValidationFailed('Medlemmet du prøver å bytte med finnes ikke.');
            }

            // Make sure target member is not logged in member
            if ($loggedInMemberId == $targetMember->id) {
                throw new RedCross_Exception_ValidationFailed('Du kan ikke bytte vakt med deg selv.'); 
            }

            // Save shift exchange request
            $result = $this->_shiftExchangeService->create($loggedInMemberId, $targetMemberId, $shiftRoleId);

            // Send email
            $this->sendRequestMail($result);

            if ($result) {
                $this->view->flashMessage()->addMessage('Forespørsel om vaktbytte har blitt sendt', RedCross_View_Helper_FlashMessage::SUCCESS);
            } else {
                $this->view->flashMessage()->addMessage('Det oppstod en feil under forespørsel om vaktbytte', RedCross_View_Helper_FlashMessage::ERROR);
            }
        }
        $this->_helper->redirector('index', 'shift', 'core');
    }

    public function cancelAction()
    {
        // TODO: ACL?
        

        $shiftExchangeId = $this->_getParam('id');
        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($shiftExchangeId)) {
            throw new RedCross_Exception_ValidationFailed('id må være et integer');
        }
        $shiftExchangeId = (int)$shiftExchangeId;

        $shiftExchange = $this->_shiftExchangeService->fetchById($shiftExchangeId);

        if (is_null($shiftExchange)) {
            throw new RedCross_Exception_ValidationFailed('Vaktbytteforespørselen du prøver å avbryte finnes ikke');
        }

        $loggedInMemberId = $this->view->authInfo()->getMemberId();
        if ($loggedInMemberId != $shiftExchange->SourceMember->id) {
            throw new RedCross_Exception_ValidationFailed($loggedInMemberId . ' != ' . $shiftExchange->SourceMember->id);
            throw new RedCross_Exception_ValidationFailed('Du eier ikke vaktbytteforespørselen du prøver å avbryte');
        }

        if (!is_null($shiftExchange->request_handled_time)) {
            throw new RedCross_Exception_ValidationFailed('Du kan ikke kansellere et vaktbytte som har blitt akseptert eller avslått.');
        }

        // send email
        $this->sendCancelMail($shiftExchange);

        $result = $shiftExchange->delete();

        if ($result > 0) {
            // TODO: Send mail to the affected members telling them that the shift 
            // exchange has been cancelled
            $this->view->flashMessage()->addMessage('Vaktbytte har blitt avbrutt', RedCross_View_Helper_FlashMessage::SUCCESS);
        } else {
            $this->view->flashMessage()->addMessage('Vaktbytte ble ikke avbrutt', RedCross_View_Helper_FlashMessage::ERROR);
        }

        $this->_helper->redirector('index', 'shift', 'core');
    }

    public function selectMemberAction()
    {
        // TODO: ACL?
        $this->_helper->acl()->isAllowed('action:core.shift', 'view');

        $shiftRoleId = $this->_getParam('id');
        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($shiftRoleId)) {
            throw new RedCross_Exception_ValidationFailed();
        } 
        $shiftRoleId = (int)$shiftRoleId;
        $this->view->shiftRoleId = $shiftRoleId;

        $ignore_courses = $this->_getParam('ignore_courses', false) != false;

        $options = array(
            Core_Gateway_Member::ELIGIBLE_OPTION_IGNORE_PASSIVE => false,
            Core_Gateway_Member::ELIGIBLE_OPTION_IGNORE_PERMANENT_PASSIVE => false,
            Core_Gateway_Member::ELIGIBLE_OPTION_IGNORE_COURSES => $ignore_courses,
            Core_Gateway_Member::SHOW_ONLY_PUBLIC_USERS => true
        );

        $shiftRole = $this->_shiftRoleService->fetch($shiftRoleId);
        $this->view->members = $this->_memberService->fetchEligibleForRole($shiftRole, $options);
        $this->view->ignore_courses = $ignore_courses;
        $this->view->memberId = $this->_authService->getIdentity()->member_id;
    }

    public function sendCancelMail($shiftExchange) {
        $mail = new RedCross_Mail_Base();
        $mail->setSubject('Forespørsel om vaktbytte avbrutt');
        $content = new Zend_View();
        $content->setScriptPath(APPLICATION_PATH . '/layouts/main/emails/');

        $shift = $shiftExchange->ShiftRole->Shift;

        $source = $shiftExchange->SourceMember;
        $target = $shiftExchange->TargetMember;

        $mail->addTo($source->getMainEmail()->address, $source->getFullName());
        $mail->addTo($target->getMainEmail()->address, $target->getFullName());

        $content->assign('sourceMember', $source);
        $content->assign('targetMember', $target);
        $content->assign('shift', $shift);
        $content->assign('event', $shift->Event);

        $body = $content->render('shift-exchange-cancel.phtml');
        try {
            $mail->setBodyText($body);
            $mail->send();
        } catch (Exception $e) {
            $this->view->flashMessage()->addMessage('Feilet å sende mail (' . $e->getMessage() . 
                ')', RedCross_View_Helper_FlashMessage::ERROR);
        }
    }
    
    public function sendRequestMail($shiftExchange) {
        $mail = new RedCross_Mail_Base();
        $mail->setSubject('Forespørsel om vaktbytte');
        $content = new Zend_View();
        $content->setScriptPath(APPLICATION_PATH . '/layouts/main/emails/');

        $shift = $shiftExchange->ShiftRole->Shift;

        $source = $shiftExchange->SourceMember;
        $target = $shiftExchange->TargetMember;

        $mail->addTo($source->getMainEmail()->address, $source->getFullName());
        $mail->addTo($target->getMainEmail()->address, $target->getFullName());

        $content->assign('sourceMember', $source);
        $content->assign('targetMember', $target);
        $content->assign('shift', $shift);
        $content->assign('event', $shift->Event);

        $body = $content->render('shift-exchange-request.phtml');
        try {
            $mail->setBodyText($body);
            $mail->send();
        } catch (Exception $e) {
            $this->view->flashMessage()->addMessage('Feilet å sende mail (' . $e->getMessage() . 
                ')', RedCross_View_Helper_FlashMessage::ERROR);
        }
    }
}

?>
